<script setup lang="ts">
import _ from 'lodash';
import type { TimeWeather, NextWeekWeather, CurrentWeather } from '@/types';
import CityWeather from '@/components/cityWeather/index.vue';
import { parseCity } from '@/api';
import { useHistoryStore } from '@/store/modules/history';
import useWeather from '@/hooks/useWeather';
const historyStore = useHistoryStore();

const viewCity = ref<string>('');
const currentWeather = ref<CurrentWeather>({});
const timeWeatherArr = ref<TimeWeather[]>([]);
const nextWeekWeatherArr = ref<NextWeekWeather[]>([]);

const getAddress = async () => {
  // 获取当前所在地经纬度
  await uni.getLocation({
    type: 'wgs84',
    success: async ({ longitude, latitude }) => {
      let res = await parseCity({
        key: 'MDSBZ-4CP3D-2FC4T-HIPEH-U6GGE-O3BU7',
        location: `${latitude},${longitude}`
      });
      // 将获取的当前城市存入缓存
      historyStore.setCurrentCity(res.result.ad_info.city);
      historyStore.setHistoryCity(res.result.ad_info.city);
      await getWeather();
    }
  });
};

const getWeather = async () => {
  const res = await useWeather(viewCity.value || historyStore.currentCity);
  currentWeather.value = res.current;
  timeWeatherArr.value = res.hourArr;
  nextWeekWeatherArr.value = res.weekArr;
};
onLoad((option) => {
  if (option?.city) {
    viewCity.value = option.city;
  }
  // 进入首页分两种，默认是当前缓存存的当前定位城市，其次是切换城市看对应城市的天气详情
  // 看对应城市的天气详情优先(viewCity有值)
  if (viewCity.value || historyStore.currentCity) {
    getWeather();
  } else {
    getAddress();
  }
});
</script>
<template>
  <view class="p30" v-if="historyStore.currentCity">
    <view class="tr">
      <navigator url="/pages/searchHistory/index" open-type="navigate" hover-class="navigator-hover" class="f-c-e ib">
        <text class="mr15 fs26">切换城市</text>
        <i class="t-icon t-icon-qiehuan"></i>
      </navigator>
    </view>

    <CityWeather
      :timeWeatherArr="timeWeatherArr"
      :nextWeekWeatherArr="nextWeekWeatherArr"
      :currentCity="viewCity || historyStore.currentCity"
      :currentWeather="currentWeather"
    />
  </view>
  <view v-else class="p30">请开启定位后再进行后续操作</view>
</template>
<style lang="scss" scoped></style>
